package dba.example.entities

import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.JoinColumn
import javax.persistence.OneToOne
import javax.persistence.PrePersist
import javax.persistence.PreUpdate
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
import scala.beans.BeanProperty
import org.hibernate.annotations.Cache
import org.hibernate.annotations.CacheConcurrencyStrategy

object Account {

  def apply() = new Account()
  def apply(username: String, password: String, name: String, company: Company) = {
    val account = new Account();
    account.username = username;
    account.password = password;
    account.name = name;
    account.company = company;
    account;
  }

}

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
class Account extends AbstractEntity {

  @Id
  @GeneratedValue
  @BeanProperty
  var id: Integer = null;

  @NotNull
  @Size(max = 100)
  @BeanProperty
  var username: String = null;

  var usernameSort: String = null;

  @NotNull
  @Size(max = 100)
  @BeanProperty
  var password: String = null;

  @NotNull
  @Size(max = 100)
  @BeanProperty
  var name: String = null;

  @BeanProperty
  var nameSort: String = null;

  @JoinColumn(name = "companyId", nullable = false)
  @OneToOne(optional = false)
  @BeanProperty
  var company: Company = null;

  /**
   * This is automatically called before the record is inserted and updated
   */
  @PrePersist
  @PreUpdate
  def updateSortColumns() {
    nameSort = if (name == null) null else name.toLowerCase();
    usernameSort = if (username == null) null else username.toLowerCase();
  }

  override def toString() = s"[id = $id, username = $username, name = $name, company = $company]"

}
